package com.demo.controller.multipart;


import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;


public class ExceptionMultipartResolver extends CommonsMultipartResolver {
    public MultipartHttpServletRequest resolveMultipart(final HttpServletRequest request) throws MultipartException {
        MultipartHttpServletRequest $request = null;
        try {
            $request = super.resolveMultipart(request);
        } catch (MultipartException e) {
            MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<String, MultipartFile>();
            Map<String, String[]> multipartParameters = new HashMap<String, String[]>();
            Map<String, String> multipartParameterContentTypes = new HashMap<String, String>();
            return new ExceptionMultipartHttpServletRequest(request, e, multipartFiles, multipartParameters,
                    multipartParameterContentTypes);
        }

        return $request;
    }

    public static class ExceptionMultipartHttpServletRequest extends DefaultMultipartHttpServletRequest {

        private MultipartException exception;
        private HttpServletRequest request;

        /**
         * @param request
         * @param mpFiles
         * @param mpParams
         * @param mpParamContentTypes
         */
        public ExceptionMultipartHttpServletRequest(HttpServletRequest request, MultipartException e,
                                                    MultiValueMap<String, MultipartFile> mpFiles, Map<String, String[]> mpParams,
                                                    Map<String, String> mpParamContentTypes) {
            super(request, mpFiles, mpParams, mpParamContentTypes);
            this.exception = e;
            this.request = request;
        }

        /**
         * @return the exception
         */
        public MultipartException getException() {
            return exception;
        }

        /**
         * @return the request
         */
        public HttpServletRequest getRequest() {
            return request;
        }

    }
}
